昨天完成了技能冷卻系統,今天接著製作遊戲開始前的說明畫面,以及遊戲結束後的結算畫面。
因為目前遊戲開始後就會直接生成目標,玩家可能還不清楚操作方式與技能效果。因此這次加入開始說明圖卡,讓玩家閱讀後再開始遊戲。另外,也加入結算畫面,顯示本場得分與最高紀錄。
這次新增UIManager,統一管理開始畫面、結算畫面與重新開始的功能。
遊戲載入時會先顯示說明圖卡,並透過Time.timeScale = 0f暫停遊戲。當玩家按下開始按鈕後,才會恢復遊戲時間。
當玩家血量歸零時,則會顯示結算畫面,並使用PlayerPrefs儲存最高分數。
using UnityEngine;
using UnityEngine.SceneManagement;
using TMPro;
public class UIManager : MonoBehaviour
{
public static UIManager Instance;
[Header("UI 面板 (圖卡容器)")]
public GameObject startPanel; // 開局說明圖卡面板
public GameObject gameOverPanel; // 結算圖卡面板
[Header("結算畫面分數顯示")]
public TextMeshProUGUI currentScoreText; // 該場得分 Text
public TextMeshProUGUI highScoreText; // 最高分數 Text
private void Awake()
{
if (Instance == null) Instance = this;
else Destroy(gameObject);
}
private void Start()
{
// 1. 當玩家從網頁進來時,預設顯示開局說明,隱藏結算面板
if (startPanel != null) startPanel.SetActive(true);
if (gameOverPanel != null) gameOverPanel.SetActive(false);
// 2. 暫停遊戲時間(生怪與計時停止運作)
Time.timeScale = 0f;
}
// 【按鈕事件】點擊「開始遊戲」
public void StartGame()
{
// 隱藏說明圖卡
if (startPanel != null) startPanel.SetActive(false);
// 恢復遊戲時間(遊戲正式運作)
Time.timeScale = 1f;
Debug.Log("遊戲正式開始!");
}
// 【觸發結算】血量歸零時呼叫
public void ShowGameOver()
{
// 1. 停止遊戲運作
Time.timeScale = 0f;
// 2. 取得當前分數與讀取最高分
int currentScore = ScoreManager.Instance != null ? ScoreManager.Instance.totalScore : 0;
int highScore = PlayerPrefs.GetInt("HighScore", 0); // 讀取最高分,沒有紀錄則為 0
// 3. 判斷是否刷新最高紀錄
if (currentScore > highScore)
{
highScore = currentScore;
PlayerPrefs.SetInt("HighScore", highScore); // 存入本地儲存
PlayerPrefs.Save();
}
// 4. 更新結算面板上的文字顯示
if (currentScoreText != null) currentScoreText.text = $"本場得分: {currentScore}";
if (highScoreText != null) highScoreText.text = $"最高紀錄: {highScore}";
// 5. 顯示結算面板圖卡
if (gameOverPanel != null) gameOverPanel.SetActive(true);
Debug.Log($"遊戲結束!本場分數: {currentScore},最高分: {highScore}");
}
// 【按鈕事件】點擊「重新開始」
public void RestartGame()
{
// 重新載入場景前先恢復時間,避免重載後繼續停格
Time.timeScale = 1f;
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
接著在原本的HealthManager中,加入血量歸零時呼叫結算畫面的判斷。
if (currentHealth <= 0)
{
if (UIManager.Instance != null)
{
UIManager.Instance.ShowGameOver();
}
}
這樣當玩家血量耗盡時,就會暫停遊戲並顯示結算畫面。玩家也能透過重新開始按鈕,再次挑戰最高分數。
今天主要完成了以下幾個部分: